package com.mflex.mwms.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;

import com.google.gson.reflect.TypeToken;
import com.mflex.mwms.R;
import com.mflex.mwms.adapter.WarehouseShelfOffDetailAdapter;
import com.mflex.mwms.model.CustomApiResult;
import com.mflex.mwms.model.ReceiveTaskRequest;
import com.mflex.mwms.model.TaskDetail;
import com.mflex.mwms.model.WarehouseShelfOffRequest;
import com.mflex.mwms.utils.MMKVUtils;
import com.mflex.mwms.utils.MessageUtils;
import com.mflex.mwms.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.CallBackProxy;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class WarehouseShelfOffDetailActivity extends BaseActivity {
    @BindView(R.id.stv_TaskNo)
    EditText stvTaskNo;

    @BindView(R.id.stv_BoxNumber)
    EditText stvBoxNumber;

//    @BindView(R.id.button_clear)
//    Button buttonClear;
//
//    @BindView(R.id.button_save)
//    Button buttonSave;

    @BindView(R.id.lvTaskDetailList)
    ListView lvTaskDetailList;

    MiniLoadingDialog mMiniLoadingDialog;

    List<TaskDetail> taskDetailList;

    private String taskNo;
    private String taskType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_warehouse_shelf_off_detail);
        ButterKnife.bind(this);
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this, "加载...");

        Intent intent = getIntent();
        Type listType = new TypeToken<ArrayList<TaskDetail>>() {
        }.getType();
        taskDetailList = (List<TaskDetail>) JsonUtil.fromJson(intent.getStringExtra("taskDetail"), listType);
        taskNo = intent.getStringExtra("taskNo");
        taskType = intent.getStringExtra("taskType");

        WarehouseShelfOffDetailAdapter warehouseShelfOffDetailAdapter = new WarehouseShelfOffDetailAdapter(this, taskDetailList);
        lvTaskDetailList.setAdapter(warehouseShelfOffDetailAdapter);

        stvTaskNo.setFocusable(false);
        stvTaskNo.setText(taskNo);
        stvBoxNumber.postDelayed(new Runnable() {
            @Override
            public void run() {
                stvBoxNumber.requestFocus();
            }
        },200);

        stvBoxNumber.setOnKeyListener(this);
//        stvShelfLocation.setOnKeyListener(this);
//        buttonClear.setOnClickListener(this);
//        buttonSave.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.button_clear:
////                clearButtonMd(view);
//                break;
//            case R.id.button_save:
////                saveButtonMd(view);
//                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && (i == 66 || i == 61)) {
            switch (view.getId()) {
                case R.id.stv_BoxNumber:
                    CheckBoxNumber(view);
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    private void CheckBoxNumber(View view) {
        boolean flag = false;
        boolean existFlag = false;
        for (TaskDetail taskDetail : taskDetailList) {
            if (StringUtils.equals(stvBoxNumber.getText().toString(), taskDetail.getDetailName()) && taskDetail.checked) {
                existFlag = true;
                break;
            }
        }
        if (existFlag) {
//            new MaterialDialog.Builder(view.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("箱号已在列表中")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(WarehouseShelfOffDetailActivity.this, "箱号已在列表中");
            return;
        }
        for (TaskDetail taskDetail : taskDetailList) {
            if (StringUtils.equals(stvBoxNumber.getText().toString(), taskDetail.getDetailName())) {
                flag = true;
//                taskDetail.setChecked(true);
//                break;
            }
        }
        if (!flag) {
//            new MaterialDialog.Builder(view.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("箱号不在该任务中")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(WarehouseShelfOffDetailActivity.this, "箱号不在该任务中");
            stvBoxNumber.setText("");
            return;
        }

        WarehouseShelfOffRequest warehouseShelfOffRequest = new WarehouseShelfOffRequest();
        warehouseShelfOffRequest.setBoxNumber(stvBoxNumber.getText().toString());
        warehouseShelfOffRequest.setTaskNo(taskNo);
        warehouseShelfOffRequest.setWarehouse(MMKVUtils.getString("Warehose", ""));
        warehouseShelfOffRequest.setTaskAction(taskType);
        warehouseShelfOffRequest.setTaskStatusName("0");
        mMiniLoadingDialog.show();
        XHttp.post("api/ShelfOff/WarehouseShelfOff")
                .upJson(JsonUtil.toJson(warehouseShelfOffRequest))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {

                    @Override
                    public void onSuccess(String response) {
                        mMiniLoadingDialog.dismiss();

                        int count = 0;
                        for (TaskDetail taskDetail : taskDetailList) {
                            if (taskDetail.isChecked()) {
                                count = count + 1;
                            }
                        }
                        if (taskDetailList.size() == count + 1) {
                            XToastUtils.success("全部下架成功", 2500);
                            //最后一个
                            setResult(0);
                            finish();
                        } else {
                            XToastUtils.success("下架成功", 2500);
                            for (TaskDetail taskDetail : taskDetailList) {
                                if (StringUtils.equals(stvBoxNumber.getText().toString(), taskDetail.getDetailName())) {

                                    taskDetail.setChecked(true);
                                }
                            }

                            Collections.sort(taskDetailList, new Comparator<TaskDetail>() {
                                @Override
                                public int compare(TaskDetail t0, TaskDetail t1) {
                                    if (!t0.isChecked() && t1.isChecked()) {
                                        return -1;
                                    }
                                    return 0;
                                }
                            });

                            WarehouseShelfOffDetailAdapter warehouseShelfOffDetailAdapter = new WarehouseShelfOffDetailAdapter(WarehouseShelfOffDetailActivity.this, taskDetailList);
                            lvTaskDetailList.setAdapter(warehouseShelfOffDetailAdapter);
                            stvBoxNumber.setText("");
                            stvBoxNumber.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    stvBoxNumber.requestFocus();
                                }
                            }, 200);
                        }
                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
                        stvBoxNumber.setText("");
                        stvBoxNumber.requestFocus();
//                        if (e.getCode() == 100) {
//                            new MaterialDialog.Builder(view.getContext())
//                                    .iconRes(R.drawable.icon_warning)
//                                    .title(R.string.tip_warning)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
//                        if (e.getCode() == 200) {
//                            new MaterialDialog.Builder(view.getContext())
//                                    .iconRes(R.drawable.icon_tip)
//                                    .title(R.string.tip_infos)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
                        MessageUtils.errorMsgAndVoice(WarehouseShelfOffDetailActivity.this, e);
                    }
                }) {
                });


    }

    private void clearButtonMd(View v) {
        stvBoxNumber.setText("");
//        stvShelfLocation.setText("");
//        stvShelfLocation.requestFocus();
        taskDetailList = new ArrayList<>();
        WarehouseShelfOffDetailAdapter warehouseShelfOffDetailAdapter = new WarehouseShelfOffDetailAdapter(this, taskDetailList);
        lvTaskDetailList.setAdapter(warehouseShelfOffDetailAdapter);
    }

    private void saveButtonMd(View v) {
        boolean flag = false;
        for (TaskDetail taskDetail : taskDetailList) {
            if (!taskDetail.isChecked()) {
                flag = true;
            }
        }
        if (flag) {
//            new MaterialDialog.Builder(v.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("箱包号没有全部扫描")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(WarehouseShelfOffDetailActivity.this, "箱包号没有全部扫描");
            return;
        }
        ReceiveTaskRequest receiveTaskRequest = new ReceiveTaskRequest();
        receiveTaskRequest.setTaskNo(taskNo);
        receiveTaskRequest.setCurrentWareHouse(MMKVUtils.getString("Warehose", ""));


    }
}